#include "gamescene.h"
#include "movingobject.h"
#include<QDebug>
#include<QMenuBar>
#include<qpainter.h>
#include<QPixmap>
#include <QMessageBox>
#include<QRect>
#include <QVBoxLayout>
#include<random>
#include<QThread>
const int TARGET_WIDTH=100;
gamescene::gamescene(QWidget *parent)
    : QMainWindow{parent}
{   label = new QLabel(this);
    this->setFixedSize(1211,800);
    this->setWindowTitle("不能死啊啊啊");
    QMenuBar *bar=menuBar();//创建菜单栏
    setMenuBar(bar);
    QMenu*startmenu=bar->addMenu("设置");
    QAction *quitaction=startmenu->addAction("退出");
    QAction *restartaction=startmenu->addAction("重新开始");
     QAction *pauseaction = startmenu->addAction("暂停");
    QAction *continueaction=startmenu->addAction("继续");
    connect(quitaction, &QAction::triggered, this, [=](){
         this->close();
     });
    connect(restartaction,&QAction::triggered,this,[=](){
        this->close();
        gamescene*game=new gamescene;
        game->show();//movingObjectLabel->move(800, 400);
        anitimer->start();
       // game->setAttribute(Qt::WA_DeleteOnClose);
        //game->resetGame(); // 重置游戏状态
        game->startmoving();
    });
    connect(pauseaction, &QAction::triggered,this, [=]() {
        if (!isPaused) {
            isPaused = true;
            anitimer->stop(); // 停止动画定时器
            //moveTimer->stop(); // 停止移动定时器
            spawnTimer->stop();
            qDebug() << "Game paused.";
        }
    });
    connect(continueaction, &QAction::triggered,this, [=]() {
        if (isPaused) { // 假设 isPaused 是一个标志变量，表示游戏是否暂停
            isPaused = false;
            // 恢复游戏逻辑，例如重新启动定时器
            anitimer->start(); // 恢复动画定时器
           // moveTimer->start(); // 恢复移动定时器
            spawnTimer->start();
        }
    });
//返回按键
    // 创建用于显示小人的 QLabel
    runningManLabel = new QLabel(this);
    runningManLabel->move(200, 400);
    // 设置小人显示的指定位置
    // 初始化动画定时器
    anitimer = new QTimer(this);
    connect(anitimer, &QTimer::timeout, this, &gamescene::updateRunningAnimation);
    anitimer->start(100);
    qDebug() << "Animation timer started!";// 每 100 毫秒更新一次动画
    // 初始化帧索引
    currentFrame = 0;

    // 初始化碰撞检测定时器
    collisionTimer = new QTimer(this);
    connect(collisionTimer, &QTimer::timeout, this, &gamescene::checkCollisions);
    collisionTimer->start(10); // 每 10ms 检测一次碰撞
    //物体移动
   // 初始化中心部件
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    //centralWidget->setLayout(layout); // 设置布局
    //setCentralWidget(centralWidget); // 设置为中心部件// 初始化图片路径
    imagePaths = {
        ":/picture/obstacle1.jpg",
        ":/picture/obstacle2.jpg",
        ":/picture/obstacle3.jpg"
    };
    // 初始化定时器
    spawnTimer = new QTimer(this);
    connect(spawnTimer, &QTimer::timeout, this, &gamescene::moveObject);
    //spawnTimer->start(2000); // 每 2 秒生成一个物体
    // 初始化倒计时显示
    countdownLabel = new QLabel(this);
    countdownLabel->setAlignment(Qt::AlignCenter);
    countdownLabel->setStyleSheet("font-size: 24px; color: red;");
    countdownLabel->setGeometry(500, 10, 200, 50); // 放置在顶部中间
    countdownLabel->setText("03:00"); // 初始显示 3 分钟

    // 初始化倒计时定时器
    countdownTimer = new QTimer(this);
    connect(countdownTimer, &QTimer::timeout, this, &gamescene::updateCountdown);
    remainingTime = 180; // 3 分钟（180 秒）
    isGameOver = false;
}

gamescene::~gamescene()
{
    // 如果定时器没有父对象，手动删除
    if (anitimer && anitimer->parent() == nullptr) {
        delete anitimer;
    }
    if (collisionTimer && collisionTimer->parent() == nullptr) {
        delete collisionTimer;
    }
    if (spawnTimer && spawnTimer->parent() == nullptr) {
        delete spawnTimer;
    }
    if (countdownTimer && countdownTimer->parent() == nullptr) {
        delete countdownTimer;
    }
    // 如果 runningManLabel 没有父对象，手动删除
    if (runningManLabel && runningManLabel->parent() == nullptr) {
        delete runningManLabel;
    }

    // 如果 movingObjects 中的对象没有父对象，手动删除
    for (MovingObject *obj : qAsConst(movingObjects)) {
        if (obj && obj->parent() == nullptr) {
            delete obj;
        }
    }
    QMutexLocker locker(&movingObjectsMutex);
    qDeleteAll(movingObjects);
    if (label) {
        label->deleteLater();
    }
    movingObjects.clear();
}

void gamescene:: paintEvent(QPaintEvent*){
    QPainter painter(this);
    QPixmap pix;
    pix.load("://picture/gamebackground.jpg");
    painter.drawPixmap(0,0,this->width(),this->height(),pix);//拉伸成窗口大小
}
void gamescene::updateRunningAnimation()
{
    if (isPaused) {
        return; // 碰撞发生后停止小人动画
    }

    // 构建当前帧的图片路径
    QString imagePath = QString(":/picture/%1.jpg").arg(currentFrame);
    QPixmap pixmap(imagePath);

    if (!pixmap.isNull()) {
        // 计算图片的宽高比
        double aspectRatio = (double)pixmap.height() / pixmap.width();
        // 根据目标宽度和宽高比计算目标高度
        int targetHeight = static_cast<int>(TARGET_WIDTH * aspectRatio);

        // 等比例缩放图片
        pixmap = pixmap.scaled(TARGET_WIDTH, targetHeight, Qt::KeepAspectRatio);
        // 显示图片
        runningManLabel->setPixmap(pixmap);
        runningManLabel->setFixedSize(TARGET_WIDTH, targetHeight);
       // qDebug() << "Image loaded successfully:" << imagePath;
    } else {
       qDebug() << "Failed to load image:" << imagePath;
    }
    // 更新帧索引
    currentFrame = (currentFrame + 1) % frameCount;
   // qDebug() << "Current frame:" << currentFrame;
    // 处理跳跃逻辑
    if (isJumping) {
        if (jumpHeight < maxJumpHeight) {
            runningManLabel->move(runningManLabel->x(), runningManLabel->y() - jumpStep); // 向上移动
            jumpHeight += jumpStep;
            //qDebug() << "Jumping - Height:" << jumpHeight << "Position:" << runningManLabel->x() << runningManLabel->y();
        }
        else {
            isJumping = false;
            //jumpHeight = 0; // 重置跳跃高度
            qDebug() << "Jump finished!";
        }
    }
    else if (jumpHeight > 0) {
        runningManLabel->move(runningManLabel->x(), runningManLabel->y() + jumpStep); // 向下移动
        jumpHeight -= jumpStep;
       // qDebug() << "Falling - Height:" << jumpHeight << "Position:" << runningManLabel->x() << runningManLabel->y();
    }
}
void gamescene::checkCollisions()
{
    // 获取跑步小人的矩形区域
    QRect manRect = runningManLabel->geometry();

    // 加锁保护 movingObjects
    QMutexLocker locker(&movingObjectsMutex);

    // 打印容器大小
    qDebug() << "movingObjects 容器大小：" << movingObjects.size();

    // 使用 QMutableListIterator 安全地遍历和修改容器
    QMutableListIterator<MovingObject*> it(movingObjects);
    while (it.hasNext()) {
       MovingObject *obj = it.next();

        // 检查对象是否有效
        if (!obj || !obj->label) {
            qDebug() << "对象无效，移除";
            it.remove();
            continue;
        }

        // 打印物体当前 X 坐标
        qDebug() << "物体当前 X 坐标：" << obj->objectX;

        // 如果物体到达目标位置，销毁它
        if (obj->objectX <= 200) {
            qDebug() << "物体到达目标位置，销毁对象：" << obj;
            if (obj->label!=0) { // 检查 label 是否有效
                if (obj->label) {
                    obj->label->hide();
                }
                obj->label->deleteLater(); // 销毁物体
            }
            it.remove();             // 从列表中移除
            delete obj;
            obj = nullptr; // 将指针置为 nullptr
            continue; // 跳过后续碰撞检测
        }

        // 检测物体是否与跑步小人碰撞
        if (obj) { // 检查指针是否有效
            obj->checkCollision(manRect);
            if (obj->collisionDetected) {
                qDebug() << "碰撞发生，停止游戏";
                // 停止所有物体的移动
                for (MovingObject *obj : qAsConst(movingObjects)) {
                    if (obj) { // 检查指针是否有效
                        obj->stopMoving();
                    }
                }

                // 停止定时器
                anitimer->stop();
                collisionTimer->stop();
                spawnTimer->stop();

                // 弹出游戏失败提示窗口
                QMessageBox::critical(this, "游戏失败", "碰撞发生，游戏结束！");

                // 退出函数，不再检测其他物体
                return;
            }
        }
    }
    qDebug() << "碰撞检测完成";
}
/*void gamescene::checkCollisions() {
    QRect manRect = runningManLabel->geometry(); // 获取跑步小人的矩形区域

    auto it = movingObjects.begin();
    while (it != movingObjects.end()) {
        MovingObject *obj = *it;
        if (obj->objectX < 200) {
            obj->label->hide(); // 隐藏物体
            obj->label->deleteLater(); // 销毁物体
            it = movingObjects.erase(it); // 从列表中移除
            continue; // 跳过后续代码
        }

        obj->checkCollision(manRect); // 检测碰撞
        if (obj->collisionDetected) {
            // 停止所有物体的移动
            for (MovingObject *obj : qAsConst(movingObjects)) {
                obj->stopMoving();
            }
            anitimer->stop();
            collisionTimer->stop();
            spawnTimer->stop();
            QMessageBox::critical(qobject_cast<QWidget*>(parent()), "游戏失败", "碰撞发生，游戏结束！");
            return;
        }
        ++it;
    }
}*/
void gamescene::startmoving()
{
    ismoving = true; // 启动物体移动
    spawnTimer->start(3000);
}
void gamescene::mousePressEvent(QMouseEvent *event)
{
    qDebug() << "Mouse button clicked:" << event->button();
    if (event->button() == Qt::LeftButton) {
        qDebug() << "Left mouse button clicked!";
        if (!isJumping) {
            isJumping = true; // 开始跳跃
        }
    }
}
void gamescene::moveObject()
{   // 如果倒计时未启动，启动它
    if (!countdownTimer->isActive()) {
        countdownTimer->start(1000); // 每秒触发一次
    }
     QMutexLocker locker(&movingObjectsMutex);
    // 随机选择一个图片路径
    std::uniform_int_distribution<int> dist(0, imagePaths.size() - 1);
    QString imagePath = imagePaths[dist(gen)];

    qDebug() << "Spawning object with image path:" << imagePath;

    // 创建 MovingObject 实例，传入图片路径
    MovingObject *obj = new MovingObject(imagePath, centralWidget());
    if (!obj) {
        qDebug() << "Failed to create MovingObject!";
        return;
    }

    // 加载图片并缩放
    QPixmap objectPixmap(imagePath); // 加载图片
    if (objectPixmap.isNull()) {
        qDebug() << "Failed to load image:" << imagePath;
        delete obj;
        return;
    }
    objectPixmap = objectPixmap.scaled(90, 90, Qt::KeepAspectRatio); // 缩放图片
    obj->label->setPixmap(objectPixmap); // 设置图片到 QLabel
    obj->label->adjustSize(); // 调整 QLabel 大小以适应图片
    obj->label->show(); // 显式显示 QLabel
    qDebug() << "Scaled image size:" << objectPixmap.size();

    obj->objectX = 800; // 随机生成初始 X 位置
    obj->objectY = 470; // 随机生成初始 Y 位置
    qDebug() << "Object initial position:" << obj->objectX << obj->objectY;

    // 设置物体的目标位置
    obj->targetX = 200; // 目标 X 位置
    obj->targetY = 470; // 目标 Y 位置

    // 移动物体到初始位置
    obj->label->move(obj->objectX, obj->objectY);
    qDebug() << "Object moved to initial position.";

    // 启动物体的移动
    obj->startMoving();
    qDebug() << "Object started moving.";

    // 将物体添加到物体列表中
    movingObjects.append(obj);
    qDebug() << "Object added to movingObjects list.";
}
void gamescene::updateCountdown()
{
    if (remainingTime > 0) {
        remainingTime--;
        int minutes = remainingTime / 60;
        int seconds = remainingTime % 60;
        countdownLabel->setText(QString("%1:%2")
      .arg(minutes, 2, 10, QChar('0'))
     .arg(seconds, 2, 10, QChar('0')));
    } else {
        countdownTimer->stop();
        checkGameResult(); // 检查游戏结果
    }
}
void gamescene::checkGameResult()
{
    if (!isGameOver) {
        bool isVictory = true;

        // 检查是否有障碍物到达目标位置
        for (MovingObject *obj : qAsConst(movingObjects)) {
            if (obj->objectX < 200) {
                isVictory = false;
                break;
            }
        }

        // 如果游戏胜利，停止定时器并隐藏所有物体
        if (isVictory) {
            anitimer->stop(); // 停止动画定时器
            spawnTimer->stop();

            // 隐藏并销毁所有物体
            for (MovingObject *obj : qAsConst(movingObjects)) {
                if (obj && obj->label) {
                    obj->label->hide();      // 隐藏物体
                    obj->label->deleteLater(); // 销毁物体
                }
                delete obj; // 释放 MovingObject 对象
            }
            movingObjects.clear(); // 清空容器

            showVictoryScreen(); // 显示胜利界面
        }
        isGameOver = true;
    }
}
void gamescene::showVictoryScreen()
{
    QDialog *victoryDialog = new QDialog(this);
    victoryDialog->setWindowTitle("游戏胜利");
    victoryDialog->setFixedSize(300, 200);

    QLabel *victoryLabel = new QLabel("恭喜你，游戏胜利！", victoryDialog);
    victoryLabel->setAlignment(Qt::AlignCenter);
    victoryLabel->setStyleSheet("font-size: 20px;");

    QVBoxLayout *layout = new QVBoxLayout(victoryDialog);
    layout->addWidget(victoryLabel);
    victoryDialog->setLayout(layout);

    victoryDialog->exec();
}
/*void hideLabel() {
    // 确保在主线程中调用
    Q_ASSERT(QThread::currentThread() == qApp->thread());

    // 隐藏 QLabel
    label->hide();
}*/
